package Utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

public class CopiereFisiereNecesare {
	public static void copyResourcesRecursively(URL originUrl, File destination) throws Exception {
	    URLConnection urlConnection = originUrl.openConnection();
	    if (urlConnection instanceof JarURLConnection) 
	        copyJarResourcesRecursively(destination, (JarURLConnection) urlConnection);
	}

	public static  void copyJarResourcesRecursively(File destination, JarURLConnection jarConnection ) throws IOException {
	    JarFile jarFile = jarConnection.getJarFile();
	    Enumeration< JarEntry> files = jarFile.entries();
	    while (files.hasMoreElements()) {
	    	JarEntry entry = files.nextElement();
	        if (entry.getName().startsWith(jarConnection.getEntryName())) {
	            String fileName = StringUtils.removeStart(entry.getName(), jarConnection.getEntryName());
	            if (!entry.isDirectory()) {
	                InputStream entryInputStream = null;
	                try {
	                    entryInputStream = jarFile.getInputStream(entry);
	                    FileUtils.copyInputStreamToFile(entryInputStream, new File(destination, fileName));
	                } finally {
	                    entryInputStream.close();
	                }
	            } else {
	                File f = new File(destination, fileName);
	                f.mkdir();
	            }
	        }
	    }
	}
	public static void copyNeededFiles (){
		
	}
	public static void main(String []a){
		copyNeededFiles();
	}
}
